package com.allenkerr.rpc.common;


import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化工具类（基于 Protostuff 实现）
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.23 17:58.
 */
public class RpcSerializationUtils {

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    private static Objenesis objenesis = new ObjenesisStd(true);

    private RpcSerializationUtils() {
    }

    /**
     * 获取类的schema
     *
     * @param tClass
     * @param <T>
     * @return
     */
    private static <T> Schema<T> getSchema(Class<T> tClass) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(tClass);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(tClass);
            if (schema != null) {
                cachedSchema.put(tClass, schema);
            }
        }
        return schema;
    }

    /**
     * 对象的序列化：对象 ——> 字节数组
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> byte[] serialize(T obj) {
        Class<T> tClass = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(tClass);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            //清除缓存
            buffer.clear();
        }
    }

    /**
     * 对象的反序列化：字节数组 ——> 对象
     *
     * @param bytes
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] bytes, Class<T> tClass) {
        try {
            /**
             * 如果一个类没有参数为空的构造方法时候，那么直接调用newInstance()方法试图得到一个实例对象的时候，
             * 会抛出异常！但是，使用new ObjenesisStd(true).newInstance()可以完美的避开这个问题。
             */
            T message = objenesis.newInstance(tClass);//实例化对象
            Schema<T> schema = getSchema(tClass);//获取类的schema
            ProtostuffIOUtil.mergeFrom(bytes, message, schema);
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

}
